package socket.thread;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import socket.SimpleServerHandler;
import socket.decoder.newFixedLength;

public class Bluetooth implements Runnable {
    //蓝牙

    private int port;
    @Override
    public void run() {
        System.out.println("--------进入蓝牙---------");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup);
            b.channel(NioServerSocketChannel.class);
            /*.option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
            .option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);*/
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    System.out.println("蓝牙过滤器"+ch.id());
                            // 注册handler
//                    ch.pipeline().addLast("framedecoder",new LengthFieldBasedFrameDecoder(1048576*20, 0, 4,0,4));

//                    ch.pipeline().addLast(new FixedLengthFrameDecoder(600));
                    /*ch.pipeline().addLast(new LineBasedFrameDecoder(1024*25));
                    ch.pipeline().addLast(new StringDecoder());*/
//                    ch.pipeline().addLast(new FixedLengthFrameDecoder(25));
//                    ch.pipeline().addLast(new newFixedLength(39));

                    ch.pipeline().addLast(new SimpleServerHandler());
                }

            });
//            b.childHandler(new ChannelFilter());
//            b.setOption("child.receiveBufferSize", 1048576*20);
            System.out.println("平台监听开启....");
            Channel ch = b.bind(5500).sync().channel();
            ch.closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //优雅的退出程序
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
